package com.weblog.follow.interceptor;

import enums.ExceptionEnum;
import exception.MyException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String header = request.getHeader("Authorization");
        if (header != null && !"".equals(header)) {
            //如果包含有Authorization头信息，就进行解析
            if (header.startsWith("Bearer")) {
                String token = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    request.setAttribute("id", claims.getId());
                } catch (MyException e) {
                    throw new MyException(ExceptionEnum.TOKEN_OUTED);
                }
            }

        }
        return true;

    }
}
